#coding:utf-8
#分离所有全局变量以及函数体

# 全局变量
# 函数

# 这个版本是暂时的，只能用来获取函数项目，架构什么的根本没有
# 而且假设.j文件完美无缺
import time
import json
from AuxClasses import *

FILE_NAME = "war3map.j"
F1 = open(FILE_NAME, "r")
def ContentSpliter_0():
    status_array = ["unknown", "parsingFunction"]
    status = "unknown"
    
    Function_Start = "function"
    Function_End = "endfunction"
    
    Functions = []
    Memory = []
    FunctionName = ""
        
    F = ArrayAsLines(PreProcess(F1.read()))
    F1.close()

    line = F.readline()

    FunctionCnt = -1
    # cnt = 0
    while line:
        # cnt += 1
        # if abs(cnt - 24076) < 10:
        #     print line, line.find(Function_End)
        # print line
        if status == "parsingFunction":
            if line.find(Function_End) < 0:
                Memory.append(line)
            else:
                Memory.append(line)
                Functions.append((FunctionName, Memory))
                Memory = []
                FunctionName = ""
                status = "unknown"
                
        elif status == "unknown":
            if line.find(Function_Start) < 0:
                pass
            else:
                status = "parsingFunction"
                FunctionCnt += 1
                FunctionName = "%d" % FunctionCnt
                Memory.append(line)
        else:
            pass
        line = F.readline()
                
    # for i in xrange(111, 120):
    #     print "==========Function:%d===========" % i
    #     print Functions[i][1]

    # print len(Functions)
    # print FunctionCnt
    # print Memory

    # cnt = 0
    # for z in Functions:
    #     if len(z[1]) > 100000:
    #         cnt += 1
    #         print z[1]
    #         time.sleep(10*1000)
    # print cnt

    return Functions
            


def PreProcess(Content):
    # 这里有个事情
    # \r的是换行
    # 没有\n
    # \r\n是字符串

    # 所以
    SafeSpliter = "XXOOXXOO"
    A = Content.replace("\r\n", SafeSpliter).split("\r")
    B = [x.replace(SafeSpliter, "\r\n") for x in A if len(x) > 0]
    return B

class ArrayAsLines:
    _cnt = 0
    _data = []
    def __init__(self, data):
        self._data = data
    def readline(self):
        if self._cnt >= len(self._data):
            return None
        else:
            D =  self._data[self._cnt] 
            self._cnt += 1
            return D

def FunctionStructureAnalyzer(FuncBlock):
    """

        function XXXX takes <type1> <varname1>,<type2> <varname2> ... returns <type>
    """
    # 获得函数的名字、变量以及返回值以及它们的类型
    try:
        FirstLine = FuncBlock._rawcode[0]
        Name = FirstLine.strip().split(" ")[1]
        ReturnType = FirstLine.strip().split(" ")[-1]
        posTAKES = FirstLine.find("takes")
        posRETURNS = FirstLine.find("returns")
        VarlistCode = FirstLine[posTAKES + 5: posRETURNS].strip()
        type_varlist = VarlistCode.split(",")
        Varlist = []
        for i in type_varlist:
            p = i.strip().split(" ")
            Varlist.append((i[0], i[1]))
    except Exception, e:
        print e


    DB = DefinitionBlock(FuncBlock._rawcode[1:-1])
    # DB._rawcode = 
    DB._name = Name
    DB._return_type = ReturnType
    DB._take_list = Varlist
    return DB



class FunctionAnalyzeWrapper:
    # _name = ""
    # _invoke_set = set()
    # _rawcode = ""
    def __init__(self, DB):
        self._invoke_set = set()
        self._name = DB._name
        self._rawcode = "\n".join(DB._rawcode)
    def add_invoke(self, FunName):
        self._invoke_set.add(FunName)
    

# main code
Function_Codes = ContentSpliter_0()
Functions = [FunctionBlock(x[1]) for x in Function_Codes]
DefBlocks = [FunctionStructureAnalyzer(x) for x in Functions]
# for i in DefBlocks:
#     if len(i._name) > 4 :
#         print i._name

#     if i._name == "VLA":
#         print "============Function %s=============" % i._name
#         for l in i._rawcode:
#             print l
#         print "============Function end============="

FunctionName = [x._name for x in DefBlocks]

FAW_List = [FunctionAnalyzeWrapper(x) for x in DefBlocks]
# print FAW_List[0]._name
for x in FAW_List:
    # if x._name == "main":
    for y in FunctionName:
        if x._rawcode.find(y) >= 0:
            x.add_invoke(y)
                # print y
    print "%s %d" % (x._name, len(x._invoke_set))

# for x in FAW_List:
print "Forming json result ......."
import json

result = {}
for x in FAW_List:
    result[x._name] = list(x._invoke_set)

open("func_invoke.json", "w").write(json.dumps(result))
    